package com.omkarpatil.learningjpa2.mapping.onetoone.sharedpk.noid;

import javax.persistence.EntityManager;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();
		
		System.out.println("##### Adding User to database ...");
		User user = new User("Mr. Anderson");

		System.out.println("##### Adding Profile to database ...");
		Profile profile = new Profile("neo@matrix.com", user);
	
		em1.persist(user);
		em1.persist(profile);
		
		em1.getTransaction().commit();
		em1.close();
		
		int userId = user.getId();
		System.out.printf("##### User Id of Mr. Anderson : %s \n", userId);
		
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em2.getTransaction().begin();
		System.out.printf("##### Fetching Profile using UserId = %s\n", userId);
		
		Profile profile2 = em2.createNamedQuery("getProfileByUserId", Profile.class)
			.setParameter("userId", userId).getSingleResult();
		
		System.out.printf("##### Profile Email : %s , User : %s", profile2.getEmail(), profile2.getUser().getName());
		
		em2.getTransaction().commit();
		em2.close();
	}

}
